// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    currentTimeStamp: 0,
    car:{},
    longitude: 113.324520,
    latitude: 23.099994,
    markers: [{
      latitude: 23.099994,
      longitude: 113.324520,
      width: 50,
      height: 50
    }],
    mmarkerssave: [{
      latitude: 23.099994,
      longitude: 113.324520,
      width: 50,
      height: 50
    }],
    polyline: [{ // 定义连线
      points: [
      ],
      color: "#FF0000DD", // 连线颜色
      width: 5, // 连线宽度
      arrowLine:true
    }],
    Date:"无",
    name:"暂无",
    age:"暂无",
    ppp1:[]
    

  },
  onLoad: function () {
    let currentTimeStamp = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8)
    this.setData({
      currentTimeStamp: currentTimeStamp
    });
    // 导航栏
    // 1.获取屏幕可使用宽度
    let windowWidth = wx.getSystemInfoSync().windowWidth;
    // 2.获取状态栏高度
    const statusBarHeight = wx.getSystemInfoSync().statusBarHeight;
    //3.获取胶囊按钮位置信息
    const menuButton = wx.getMenuButtonBoundingClientRect();
    this.setData({
      navtop:menuButton.top
    })
  },
  onShow(){

    this.mapCtx = wx.createMapContext('map');
    const that=this
    const app =getApp()
    app.fetchData().then(data => {
      // 数据请求成功，可以在这里进行页面加载操作
      that.setData({
        openid:app.globalData.openid
      })
    })

    wx.request({
      url: 'https://dj.ifankui.com/api/usr/getProfile',
      method:'POST',
      data:{
        openid:app.globalData.openid,
        
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res){

        console.log(res);
        console.log(res.data.data.headimg);
        that.setData({
          img:res.data.data.headimg,
        },()=>{
          if(res.data.data.lrxm.length==0){
            return
          }
          that.setData({
            name:res.data.data.lrxm,
            age:app.globalData.age
          })
        })
      }
    })

  
  },
  onHide(){
    const that=this
    setTimeout(function() {
      that.setData({
        currentTimeStamp: 0,
        car:{},
        longitude: 113.324520,
        latitude: 23.099994,
        markers: [{
          latitude: 23.099994,
          longitude: 113.324520,
          width: 50,
          height: 50
        }],
        polyline: [{ // 定义连线
          points: [
          ],
          color: "#FF0000DD", // 连线颜色
          width: 2, // 连线宽度
          dottedLine: false // 是否虚线
        }],
        Date:"无",
        name:"暂无",
        age:"暂无",
      })
    }, 1000); // 2 秒后执行匿名函数
  },
  

bindDateChange(e){
  console.log(e);
  this.setData({
    Date:e.detail.value
  },()=>{
    this.getDate()
    console.log(this.data.Date);
  })
},

getDate(){
  const app =getApp()
  const that = this
  console.log(app.globalData.device_code);
  wx.request({
    url: 'https://dj.ifankui.com/api/device/getDeviceHistoryByDay',
    method: "POST",
    data: {
      openid: this.data.openid,
      device_code:app.globalData.device_code,
      day:this.data.Date
    },
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    success(res){
      const markers1=[]
      const polyline=[]
      let ppp=[]
      console.log(res);
      res.data.history.forEach(element => {
        if(element.loc.length>1){
          ppp.push(element)
        }
      
     
      }); 
      that.setData({ppp1:ppp})
      ppp.forEach((element,index)=>{
        console.log(index,res.data.history.length-1);
        var pp3=''
        if(index==ppp.length-1){
            pp3="终点:"
            
        }else if(index==0){
          pp3="起点:"
        }
        console.log(pp3);
        if(element.loc.length>1){
          const pp=element.loc.split(',')
          const pp2=element.dt.split(' ')
          
          console.log(pp[0],pp[1]);
          pp2[1]=pp2[1].slice(0, -3)
          console.log(pp[1]);
          const marker={
            id:index,
            latitude: pp[1],
            longitude: pp[0],
            width: 20,
            height: 20,
            callout: {
              content: pp3+pp2[1], // 标记内容
              color: '#000000', 
              fontSize: 12, 
              borderRadius: 5, 
              bgColor: '#ffffff', 
              padding: 2,
              display: 'BYCLICK' // 始终显示文字标签
            }
          }
          const polyline1={
            latitude: pp[1], longitude: pp[0],
          }
          polyline.push(polyline1)
          markers1.push(marker)
        }
      })
      that.setData({
        markers:markers1,
        mmarkerssave:markers1,
        'polyline[0].points': polyline
      },()=>{
        that.startAnimation();
        console.log(that.data.markers);
        that.setData({
          includePoints:that.data.markers.map(marker => ({
            latitude: marker.latitude,
            longitude: marker.longitude
          }))
        });
        console.log(that.data.polyline);

      })
    }
  })
}
,
tiao(){

  wx.navigateTo({
    url: '../user/user',
  })
},
stepIncrease() {
  let value = 0;
  return function() {
    if (value < 1) {
      value += 0.05;
      if (value > 1) {
        value = 1;
      }
      console.log(value);
      return value;
    } else {
      return 1;
    }
  };
},
startAnimation() {
  const that=this
  let timer
  let index = 0;
  const path = this.data.polyline[0].points;
  console.log(path);
  let progress=0
  let i=0
  if(path.length>=2){
    console.log("第");
    timer=setInterval(() => {
      i=i+1
      console.log(i);
      let start = path[index];
      let end = path[index + 1];
      if(progress<=1){
        progress=progress+0.1
      }
      let newLat = parseFloat(start.latitude)+(end.latitude - start.latitude)*progress;
      let newLng = parseFloat(start.longitude)+(end.longitude - start.longitude)*progress;
      let angle = this.getAngle(start.latitude, start.longitude, end.latitude, end.longitude);
      // 更新标记位置
      if(i==1){
        this.setData({
          markers: [
            { id: 1, 
            latitude: newLat, 
            longitude: newLng ,
            width: 50,
            height: 50,
            iconPath:'/images/666.png',
            rotate: angle,
          }]
        },()=>{      console.log("创建");
          if (progress>=0.95) {
            progress=0
            console.log(progress);
            index=index+1
            console.log(index,path.length - 1);
            if (index == path.length - 1) {
              clearInterval(timer);
              setTimeout(() => {
                that.setData({
                  markers: []
                },()=>{
                  that.setData({
                    markers: that.data.mmarkerssave
                  },1000);
    
                });
    
              }, 100); // 延迟 100 毫秒
            }
          }});
      }else{
        this.setData({
          [`markers[0].latitude`]: newLat,
          [`markers[0].longitude`]: newLng,
          [`markers[0].rotate`]: angle
        },()=>{      console.log("更新");
          if (progress>=0.95) {
            progress=0
            console.log(progress);
            index=index+1
            console.log(index,path.length - 1);
            if (index == path.length - 1) {
              clearInterval(timer);
              setTimeout(() => {
                that.setData({
                  markers: []
                },()=>{
                  that.setData({
                    markers: that.data.mmarkerssave
                  },1000);
    
                });
    
              }, 100); // 延迟 100 毫秒
            }
          }});
      }

  }, 200); // 100ms更新一次

  }




},

getAngle(lat1, lng1, lat2, lng2) {
  let radLat1 = lat1 * Math.PI / 180;
  let radLat2 = lat2 * Math.PI / 180;
  let deltaLng = (lng2 - lng1) * Math.PI / 180;

  let y = Math.sin(deltaLng) * Math.cos(radLat2);
  let x = Math.cos(radLat1) * Math.sin(radLat2) - Math.sin(radLat1) * Math.cos(radLat2) * Math.cos(deltaLng);
  
  let angle = Math.atan2(y, x) * 180 / Math.PI;
  
  // 调整角度 +180 使箭头与路径方向一致
  return (angle + 180) % 360; // 将角度调整到 0-360 范围内
}
})